import { onBeforeUnmount, onMounted, ref } from "vue"
import { getValueByModel } from "../util"
import { logInfo } from "../log"

/**
 * 复制功能
 * @param SelectState 
 * @param currentView 
 * @param props 
 */
export const useCopy = function (
    SelectState: SelectCellStateResult, 
    currentView: CurrentViewResult, 
    props: Props
) {
    onMounted(() => { document.addEventListener('keydown', keydownHandel) })
    onBeforeUnmount(() => document.removeEventListener('keydown', keydownHandel))

    function keydownHandel(e: KeyboardEvent){
        if (!currentView.checkCurrentView()) return;
        if ((e?.ctrlKey || e?.metaKey) && e?.keyCode == 67) {
            copyHandel()
        }
    }

    function copyHandel(){
        // logInfo("开始复制")

        const colSplitCode = '\t'
        const rowSplitCode = '\r'
    
        const { startX, endX, startY, endY } = SelectState.selectCellState.value
        const minX = Math.min(startX!, endX!)
        const maxX = Math.max(startX!, endX!)
        const minY = Math.min(startY!, endY!)
        const maxY = Math.max(startY!, endY!)
    
        const result: string[] = []
        for (let y = minY; y <= maxY; y++ ) {
            const data: string[] = []
            for ( let x = minX; x <= maxX; x++ ) {
                data.push(getCellValue(y, x))
            }
            result.push(data.join(colSplitCode))
        }

        copyTextToClipboardFallback(result.join(rowSplitCode))
        
    }

    function getCellValue(rowindex: number, colindex: number){

        const column = props.columns[colindex]
        const record = props.dataSource[rowindex]

        if (typeof column.customCopy === 'function') {
            return column.customCopy({
                rowIndex: rowindex,
                colIndex: colindex,
                column: column,
                record: record,
                text: getValueByModel(column.dataIndex, record)
            })
        }

        const dataIndex = column.dataIndex
        const value = getValueByModel(dataIndex, record)

        // 配置了选项
        if (column.options){
            // 多选
            if (column.type === 'checkbox') {
                return value.map((v: any) => column.options?.find(item => item.value === v)?.label ?? v ?? '').join(',')
            } 
            // 单选
            else {
                return column.options.find(item => item.value === value)?.label ?? value ?? ''
            }
            
        } 
        else {
            return value ?? ''
        }
    }

    async function copyTextToClipboardFallback(text: string) {
        try {

            return await navigator.clipboard.writeText(text)

        } catch (e) {

            const textarea = document.createElement("textarea");
            textarea.value = text;
            textarea.setAttribute('style', 'opacity: 0; height: 1px;')
            textarea.setAttribute('readonly', 'readonly');
            document.body.appendChild(textarea);
            textarea.select();
            textarea.setSelectionRange(0, 999999);
            document.execCommand("copy");
            document.body.removeChild(textarea);

        }
    }

    return { copyHandel }

}